package com.central.apps.controller;

import com.central.app.common.feign.SystemClient;
import com.central.app.service.HandlerService;
import com.central.app.service.impl.FlowCommonServiceImpl;
import com.central.bizcommon.model.flow.FlowGroup;
import com.central.bizcommon.model.flow.FlowTask;
import com.central.common.auth.details.LoginAppUser;
import com.central.common.util.SysUserUtil;
import com.central.common.web.PageResult;
import com.central.common.web.Result;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @Author mengweitao
 * @Date 2022/12/22 10:10
 * 离职员工权限转移
 */
@Log4j2
@RestController
@RequestMapping("/permissionTransfer")
public class PermissionTransferController {

    @Autowired
    private HandlerService handlerService;
    @Autowired
    private FlowCommonServiceImpl flowCommonService;
    @Autowired
    private SystemClient systemClient;

    //校验离职员工，是否有未完成的追踪单，是否占用物料
    @PostMapping("/userPermissionTransferCheck")
    public Result userPermissionTransferCheck(@RequestBody Map<String, Object> param) {
        //判断离职人是否有未完成的追踪单
        String quitUserId = MapUtils.getString(param, "quitUserId");//离职人id  sys_user里的id
//        String transfereeId = MapUtils.getString(param, "transfereeId");//被转交人id  sys_user里的id

        List<Map<String, Object>> bySql = handlerService.findBySql("select * from gq_materialusenew where createuser = " + quitUserId + " and materialgoing = '未使用'");
        if (CollectionUtils.isNotEmpty(bySql)) {
            return Result.failed(bySql, "该离职人员需先进行贵重物料转移，否则不予办理权限转移");
        }
        //判断离职人是否占用库存物料
        List<Map<String, Object>> bySql1 = handlerService.findBySql("select * from gq_invbalances where applyby = ( select field10 from sys_user where id = '" + quitUserId + "' )");
        if (CollectionUtils.isNotEmpty(bySql1)) {
            return Result.failed(bySql1, "该离职人员需先申请取消个人占用，否则不予办理权限转移");
        }
        return Result.succeed("该用户可以进行权限转移");
    }

    //权限转移
    @PostMapping("/userPermissionTransfer")
    @Transactional(rollbackFor = Exception.class)
    public Result userPermissionTransfer(@RequestBody Map<String, Object> param) throws Exception {
        try {
            //判断离职人是否有未完成的追踪单
            String userName = null;//用户的username用户账号
            String quitUserId = MapUtils.getString(param, "quitUserId");//离职人id  sys_user里的id
            String transfereeId = MapUtils.getString(param, "transfereeId");//被转交人id  sys_user里的id
            if(StringUtils.isBlank(quitUserId)&&StringUtils.isBlank(transfereeId)){
                return Result.failed("未选择离职人，被转交人。");
            }

            List<Map<String, Object>> bySql = handlerService.findBySql("select id,username from sys_user where id in ('" + quitUserId + "','"+transfereeId+"')");
            Map<String, Object> userMap = new HashMap<>();
            if (CollectionUtils.isNotEmpty(bySql)) {
                for (Map<String, Object> map : bySql) {
                    userMap.put(MapUtils.getString(map,"id"),MapUtils.getString(map,"username"));
                }
            }

            /**
             * 5、将被转交人加入离职人员所在项目组；
             * 6、对于已经完成的流程，为解决被转交人对此流程的可见性问题，可增加抄送人方式解决；（分期付款的场景，待办事项通知）  暂不实现
             * 7、对于还在处理中的流程，如离职人员正在处理或流程尚未到达离职人员，可直接更换流程处理人；   已实现
             * 8、除了主要流程外，与离职人员相关的变更流程，也做相应处理；  需要admin去手动修改流程图节点
             * 9、将该离职员工从项目组名单中移除，至于该离职员工的组织架构信息，由OA处理后，同步给ERP；   修改一下用户状态为已注销
             * 10、禁止该离职员工登录ERP系统，包括从OA中单点登录到ERP；   修改用户状态为已注销
             */
            //7.查找离职人是否正在处理的流程，更换流程处理人
            //1.当前为离职人代办的。转移给被转交人
            //2.不是当前代办的，去修改流程模板里节点人

            //离职人员代办的
            pendingFlow(userMap,quitUserId,transfereeId);
            //流程模型节点涉及到离职人的，转移给被转交人  需要admin手动修改节点信息

            //5、将被转交人加入离职人员所在项目组；
            transferProject(quitUserId,transfereeId);

            //8、除了主要流程外，与离职人员相关的变更流程，也做相应处理；角色，用户组
            //处理岗位角色
            handlerPost(quitUserId,transfereeId,userMap);


            //变更离职人得状态为注销
            List<Map<String, Object>> bySql1 = handlerService.findBySql("select worknumber from sys_user where id = '" + quitUserId + "'");
            systemClient.logicDels(MapUtils.getString(bySql1.get(0),"worknumber"));
            return Result.succeed("权限转移成功");
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.failed(e.getMessage());
        }
    }


    /**
     *
     * @param userMap  人id，username的map
     * @param quitUserId  离职人
     * @param transfereeId   被转交人
     * @throws Exception
     */
    public void pendingFlow(Map<String, Object> userMap, String quitUserId, String transfereeId) throws Exception {
        String userName = MapUtils.getString(userMap, quitUserId);
        List<FlowTask> flowTasks = new ArrayList<>();
        if (StringUtils.isNotBlank(userName)) {
            Map<String, Object> map = new HashMap<>();
            map.put("page", "1");
            map.put("limit", "10000");
            map.put("user", userName);
            PageResult<FlowTask> todoTasks = flowCommonService.findTodoTasks(map);
            flowTasks = todoTasks.getData();
        }

        if (CollectionUtils.isNotEmpty(flowTasks)) {
            for (FlowTask flowTask : flowTasks) {
                String taskId = flowTask.getId();
                if (StringUtils.isNotBlank(flowTask.getAssignee())) {
                    if (flowTask.getAssignee().equals(userName)) {
                        handlerService.findBySql("update ACT_RU_TASK set ASSIGNEE_ = '" + MapUtils.getString(userMap, transfereeId) + "' where ID_ = '" + taskId + "'");
                    }
                }
                List<Map<String, Object>> bySql1 = handlerService.findBySql("select ID_ as id,USER_ID_ as userid from ACT_RU_IDENTITYLINK where TASK_ID_ = '" + taskId + "'");
                if (CollectionUtils.isNotEmpty(bySql1)) {
                    for (Map<String, Object> map : bySql1) {
                        String userid = MapUtils.getString(map, "userid");
                        String id = MapUtils.getString(map, "id");
                        if (userid.equals(userName)) {
                            handlerService.findBySql("update act_ru_identitylink set USER_ID_ = '" + MapUtils.getString(userMap, transfereeId) + "' where ID_ = '" + id + "'");
                        }
                    }
                }
            }
        }
    }


    /**
     *
     * @param quitUserId 离职人id
     * @param transfereeId 被转交人id
     */
    public void transferProject(String quitUserId, String transfereeId){
        List<Map<String, Object>> bySql = handlerService.findBySql("select id from gq_proresourcesdetail where prid in ( select field10 from sys_user where id = '" + quitUserId + " ' )");

        List<Map<String, Object>> bySql1 = handlerService.findBySql("select field10 from sys_user where id = '" + transfereeId + "'");
        String field10 = "";
        String name = "";
        if(CollectionUtils.isNotEmpty(bySql1)){
            Map<String, Object> map = bySql1.get(0);
            field10 = MapUtils.getString(map, "field10");
            List<Map<String, Object>> bySql2 = handlerService.findBySql("select name from gq_person where id = '" + field10 + "'");
            if(CollectionUtils.isNotEmpty(bySql2)){
                Map<String, Object> map1 = bySql2.get(0);
                name = MapUtils.getString(map1, "name");
            }
        }
        if(CollectionUtils.isNotEmpty(bySql)){
            for (Map<String, Object> map : bySql) {
                handlerService.findBySql("update gq_proresourcesdetail set prid = '" + field10 + "' , prname = '" + name + "' where id = '" + MapUtils.getString(map,"id") + "'");
            }
        }
    }


    /**
     *
     * @param quitUserId  离职人id
     * @param transfereeId  被转交人id
     * @param userMap  人id，username的map
     */
    //处理岗位角色
    public void handlerPost(String quitUserId,String transfereeId,Map<String,Object> userMap){
        List<Map<String, Object>> bySql1 = handlerService.findBySql("select id as deptid,code from sys_dept where code = (SELECT deptcode from sys_user where id ='" + transfereeId + "')");
        String deptid = MapUtils.getString(bySql1.get(0), "deptid");
        String code = MapUtils.getString(bySql1.get(0), "code");

        LoginAppUser loginAppUser = SysUserUtil.getLoginAppUser();

        List<Map<String, Object>> bySql = handlerService.findBySql("select DISTINCT groupid from act_cus_group_membership where userid = '" + quitUserId + "'");
        if(CollectionUtils.isNotEmpty(bySql)){
            for (Map<String, Object> map : bySql) {
                String groupid = MapUtils.getString(map, "groupid");
                handlerService.findBySql("delete from act_cus_group_membership where groupid = '" + groupid + "' and userid = '" + quitUserId + "'");

                //将被转交人放到岗位角色中
                String cusGroupId = UUID.randomUUID().toString().replace("-", "");
                String transfereeName = MapUtils.getString(userMap, transfereeId);
                handlerService.findBySql("insert into act_cus_group_membership (id,userid,username,groupid,supervise_ids,deptid,createuser,delflag) values ('"+
                        cusGroupId + "','" +transfereeId + "','" + transfereeName + "','" + groupid + "','" + code + "','" + deptid + "','" + loginAppUser.getId() + "','" + 0 + "')");
            }
        }
    }


}
